<?php
namespace app\api\business;


use app\lib\IdWork;
use app\lib\Key;
use app\model\mysql\OrderProduct;
use app\model\mysql\ProductSku;
use think\Exception;
use think\facade\Cache;
use think\facade\Log;
use think\facade\Db;

class Order {

    protected $model;
    protected $orderProductModel;

    public function __construct() {
        $this->model = new \app\model\mysql\Order();
        $this->orderProductModel = new OrderProduct();
    }

    public function save($params = []) : array {

        if ($params["address_id"] <= 0 || empty($params["ids"]) || $params["user_id"] <= 0) {
            return [];
        }

        try{
            $cartItems = Cache::hMGet(Key::getCartKey($params["user_id"]), array_map(function ($value){
                return Key::getCartHashKey($value);
            }, $params["ids"]));
            unset($params["ids"]);

            $cartItems = array_map(function ($value){
                return $value != false ? json_decode($value, true) : null;
            }, $cartItems);
            $cartItems = array_filter($cartItems);
            if (empty($cartItems)) {
                return [];
            }
            $skuIds = array_column($cartItems, "sku_id");
            $cartItems = array_combine($skuIds, $cartItems);
            $skuList = (new ProductSku())->field("id, price, product_id, stock")->whereIn("id", $skuIds)->select();
            $skuList = $skuList->toArray();
            if (empty($skuList)) {
                return [];
            }

            $params["total_price"] = 0;
            $params["order_id"] = (string)IdWork::getInstance()->setWorkId(mt_rand(0, 10))->nextId();
            $orderSkus = [];
            foreach ($skuList as $sku) {
                if (isset($cartItems[$sku["id"]])) {
                    if ($sku["stock"] <= $cartItems[$sku["id"]]["num"]) {
                        throw new  Exception($cartItems[$sku["id"]]["title"] .  " 库存不够，无法下单");
                    }
                }
                $params["total_price"] +=  $sku["price"] * $cartItems[$sku["id"]]["num"];
                $orderSkus[] = [
                    "order_id" => $params["order_id"],
                    "sku_id" => $sku["id"],
                    "product_id" => $sku["product_id"],
                    "num" => $cartItems[$sku["id"]]["num"],
                    "price" => $sku["price"],
                    "title" => $cartItems[$sku["id"]]["title"],
                    "image" => $cartItems[$sku["id"]]["image"],
                ];
            }
            try{

                Db::startTrans();
                $result1 = $this->model->saveData($params);
                $result2 = $this->orderProductModel->saveAllData($orderSkus);
                Db::commit();
                if (!$result1 || !$result2) {
                    return [];
                }
                (new Cart())->mHDel($params["user_id"], $skuIds);
            }catch (Exception $e){
                Log::error($e);
                Db::rollback();
            }

            return ["id" => $params["order_id"]];
        }catch (Exception $e){
            Log::error($e);
            return [];
        }


    }

    public function detail($orderId = 0) : array {
        if ($orderId <= 0) {
            return [];
        }

        $result = [];

        try{

            $order = $this->model->where("order_id", $orderId)->find();
            if (!$order) {
                return [];
            }
            $result["id"] = $orderId;
            $result["price"] = $order->total_price;
            $result["consignee_info"] = "江西省 上饶市 鄱阳县xxx 王新华收 180xxxx";
            $result["create_time"] = $order->created_time;
            $result["pay_time"] = $order->pay_time;
            $result["tilte"] = "";
            $result["goods"] = [];

            $orderItems = $this->orderProductModel->where("order_id", $orderId)->select();
            $orderItems = $orderItems->toArray();
            foreach ($orderItems as $item) {
                $result["goods"][] = [
                    "id" => $item["id"],
                    "title" => $item["title"],
                    "price" => $item["price"],
                    "num" => $item["num"],
                    "image" => $item["image"],
                    "sku" => "",
                ];
            }
            return $result;
        }catch (Exception $e){
            Log::error($e);
            return [];
        }

    }

}